package com.donger.business.upms.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.donger.business.upms.entity.SysDict;
import com.donger.business.upms.entity.SysDictItem;
import com.donger.business.upms.service.ISysDictItemService;
import com.donger.business.upms.service.ISysDictService;
import com.donger.common.core.utils.Res;
import com.donger.common.core.utils.Result;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xyx
 * @since 2019-01-12
 */
@AllArgsConstructor
@RestController
@RequestMapping("/sys/dict")
public class SysDictController {

    private static final String MODULE_NAME = "系统字典管理";

    private final ISysDictService sysDictService;

    private final ISysDictItemService sysDictItemService;

    /**
     * 查询字典列表
     */
    @GetMapping("page")
    public Result<IPage<SysDict>> page(Page<SysDict> page, SysDict sysDict) {
        return Res.ok(sysDictService.page(page, new QueryWrapper<SysDict>().lambda()
                .like(StrUtil.isNotBlank(sysDict.getName()), SysDict::getName, sysDict.getName())
                .like(StrUtil.isNotBlank(sysDict.getType()), SysDict::getType, sysDict.getType())
        ));
    }

    /**
     * 查询字典列表
     */
    @GetMapping("list")
    public Result list(SysDict sysDict) {
        return Res.ok(sysDictService.list(new QueryWrapper<SysDict>().lambda()
                .like(StrUtil.isNotBlank(sysDict.getName()), SysDict::getName, sysDict.getName())
        ));
    }

    /**
     * 查询字典信息
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("@pms.hasPermission('sys:dict:info')")
    public Result<SysDict> info(@PathVariable("id") Long id) {
        return Res.ok(sysDictService.getById(id));
    }

    /**
     * 保存字典
     */
    @PostMapping("/save")
    @PreAuthorize("@pms.hasPermission('sys:dict:save')")
    public Result<Boolean> save(@RequestBody SysDict dict) {
        return Res.ok(sysDictService.save(dict));
    }

    /**
     * 修改字典
     */
    @PostMapping("/update")
    @PreAuthorize("@pms.hasPermission('sys:dict:update')")
    public Result<Boolean> update(@RequestBody SysDict dict) {
        return Res.ok(sysDictService.updateById(dict));
    }

    /**
     * 删除字典
     */
    @DeleteMapping("/delete/{dictId}")
    @PreAuthorize("@pms.hasPermission('sys:dict:del')")
    public Result<Boolean> delete(@PathVariable("dictId") Long dictId) {
        List<SysDictItem> item = sysDictItemService.list(new QueryWrapper<SysDictItem>().lambda().eq(SysDictItem::getDictId, dictId));
        if (CollUtil.isNotEmpty(item)) {
            return Res.error("请删除子项后删除该字典");
        }
        return Res.ok(sysDictService.removeById(dictId));
    }

    /**
     * 根据type 查询字典
     *
     * @param type
     * @return
     */

    @GetMapping("/type/{type}")
    public Result<List<HashMap>> getByType(@PathVariable("type") String type) {

        List<HashMap> list = sysDictItemService.list(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getType, type))
                .stream().map(item -> {
                    HashMap<String, String> hashMap = new HashMap<>(2);
                    hashMap.put("value", item.getItemCode());
                    hashMap.put("label", item.getItemText());
                    return hashMap;
                }).collect(Collectors.toList());

        return Res.ok(list);
    }

    /**
     * 根据字典ID查询子字典项
     *
     * @param page
     * @param sysDictItem
     * @return
     */
    @GetMapping("/item/list")
    public Result<IPage<SysDictItem>> typeList(Page<SysDictItem> page, SysDictItem sysDictItem) {
        return Res.ok(sysDictItemService.page(page, new QueryWrapper<SysDictItem>().lambda()
                .eq(sysDictItem.getDictId() != null, SysDictItem::getDictId, sysDictItem.getDictId())
                .like(StrUtil.isNotBlank(sysDictItem.getItemText()), SysDictItem::getItemText, sysDictItem.getItemText())
                .like(StrUtil.isNotBlank(sysDictItem.getItemCode()), SysDictItem::getItemCode, sysDictItem.getItemCode())
        ));
    }

    @GetMapping("/item/info/{id}")
    @PreAuthorize("@pms.hasPermission('sys:dict:item:info')")
    public Result<SysDictItem> itemInfo(@PathVariable("id") Long id) {
        return Res.ok(sysDictItemService.getById(id));
    }

    @PostMapping("/item/save")
    @PreAuthorize("@pms.hasPermission('sys:dict:item:save')")
    public Result<Boolean> saveItem(@RequestBody SysDictItem sysDictItem) {
        SysDict sysDict = sysDictService.getOne(new QueryWrapper<SysDict>().lambda().eq(SysDict::getId, sysDictItem.getDictId()));
        sysDictItem.setType(sysDict.getType());
        return Res.ok(sysDictItemService.save(sysDictItem));
    }

    @PostMapping("/item/update")
    @PreAuthorize("@pms.hasPermission('sys:dict:item:update')")
    public Result<Boolean> updateItem(@RequestBody SysDictItem sysDictItem) {
        SysDict sysDict = sysDictService.getOne(new QueryWrapper<SysDict>().lambda().eq(SysDict::getId, sysDictItem.getDictId()));
        sysDictItem.setType(sysDict.getType());
        return Res.ok(sysDictItemService.updateById(sysDictItem));
    }

    @DeleteMapping("/item/delete/{id}")
    @PreAuthorize("@pms.hasPermission('sys:dict:item:del')")
    public Result<Boolean> deleteItem(@PathVariable("id") Long id) {
        return Res.ok(sysDictItemService.removeById(id));
    }

    @DeleteMapping("/item/deleteList")
    @PreAuthorize("@pms.hasPermission('sys:dict:item:del')")
    public Result<Boolean> deleteItemList(@PathParam("ids") String ids) {
        return Res.ok(sysDictItemService.remove(new LambdaQueryWrapper<SysDictItem>().in(SysDictItem::getId, ids.split(","))));
    }
}

